package com.ddw.wotcg.client;

import com.ddw.wotcg.client.resources.Resources;
import com.ddw.wotcg.client.threejs.Detector;
import com.ddw.wotcg.client.threejs.cameras.PerspectiveCamera;
import com.ddw.wotcg.client.threejs.core.Geometry;
import com.ddw.wotcg.client.threejs.extras.geometries.CubeGeometry;
import com.ddw.wotcg.client.threejs.materials.Material;
import com.ddw.wotcg.client.threejs.materials.MeshBasicMaterial;
import com.ddw.wotcg.client.threejs.materials.MeshBasicMaterial.MeshBasicMaterialParameters;
import com.ddw.wotcg.client.threejs.math.Vector3;
import com.ddw.wotcg.client.threejs.objects.Mesh;
import com.ddw.wotcg.client.threejs.renderers.CanvasRenderer;
import com.ddw.wotcg.client.threejs.renderers.Renderer;
import com.ddw.wotcg.client.threejs.renderers.WebGLRenderer;
import com.ddw.wotcg.client.threejs.scenes.Scene;
import com.google.gwt.animation.client.AnimationScheduler;
import com.google.gwt.animation.client.AnimationScheduler.AnimationCallback;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;

/**
 * Represents the entry point for the application
 * 
 * @author fungus1487
 * 
 */
public class Game implements EntryPoint {
	
	private AnimationCallback render;
	
	@Override
	public void onModuleLoad() {
		Resources.INSTANCE.css().ensureInjected();
		
		// Get the game element to show in
		final Element gameEl = Document.get().getElementById("__game");
		final int innerWidth = gameEl.getOffsetWidth();
		final int innerHeight = gameEl.getOffsetHeight();
		
		// Create a scene, camera and renderer to render to
		final Scene scene = Scene.create();
		final PerspectiveCamera camera = PerspectiveCamera.create(75,
				(double) innerWidth / (double) innerHeight, 0.1, 1000);
		final Renderer renderer = Detector.webgl() ? WebGLRenderer.create()
				: CanvasRenderer.create();
		renderer.setSize(innerWidth, innerHeight);
		gameEl.appendChild(renderer.getDomElement());
		
		// Create a cube to display
		final Geometry geometry = CubeGeometry.create(1, 1, 1);
		final MeshBasicMaterialParameters materialParams = MeshBasicMaterialParameters
				.create();
		materialParams.setColor(0x00ff00);
		final Material material = MeshBasicMaterial.create(materialParams);
		final Mesh cube = Mesh.create(geometry, material);
		scene.add(cube);
		
		camera.getPosition().setZ(5);
		
		this.render = new AnimationCallback() {
			
			@Override
			public void execute(double timestamp) {
				AnimationScheduler.get()
						.requestAnimationFrame(Game.this.render);
				
				final Vector3 rotation = cube.getRotation();
				rotation.setX(rotation.getX() + 0.1);
				rotation.setY(rotation.getY() + 0.1);
				
				renderer.render(scene, camera);
			}
			
		};
		
		// Hide the splash screen
		Document.get().getElementById("__splash").removeFromParent();
	}
	
}
